package com.small.handler;

import java.lang.reflect.Field;
import java.util.Set;
import org.apache.log4j.Logger;
import com.small.annotation.Inject;

/**
 * Ioc注入处理类
 * <br/>支持接口使用注入
 * @author 乐乐
 *
 */
public class IocHandler {
  private static final Logger logger = Logger.getLogger(IocHandler.class);
  /**
   * Ioc注入初始化
   * @throws InstantiationException 
   * @throws IllegalAccessException 
   * @throws IllegalArgumentException 
   */
  public static void init() {
    
    //获取所有类
    Set<Class<?>> classes = ClassHelper.getClassAll(); 
    
    for (Class<?> clazz : classes) {
      
      //获取当前类
      Field[] fields = clazz.getDeclaredFields();
      //设置私有属性的访问权限
      Field.setAccessible(fields, true);
      for (Field field : fields) {
        
        //判断当前属性是否使用了Inject注入注解
        if (field.isAnnotationPresent(Inject.class)) {
          
          //获取当前属性的值
          Class<?> fieldType = field.getType();
          
          Inject cInject = field.getAnnotation(Inject.class);
          
          Class<?> value = null;
          
          try {
            //判断是不是接口
            if (fieldType.isInterface()) {   //注入接口需传值
              
              if (null != cInject.value()) {
                value = cInject.value();
                if (null == BeanHelper.getBean(clazz)) {  //获取bean中是否有当前类的实例对象
                  BeanHelper.setBean(clazz, clazz.newInstance());
                }
                if (null == BeanHelper.getBean(value)) {
                  BeanHelper.setBean(value, value.newInstance());
                }
                field.set(BeanHelper.getBean(clazz), BeanHelper.getBean(value));
              }else {
                //注入接口不可不传值
              }
              
            }else {    //注入对象不可传值
              
              if (null == cInject.value()) {
                if (null == BeanHelper.getBean(clazz)) {   //存在属性使用注入的默认转成bean
                  BeanHelper.setBean(clazz, clazz.newInstance());
                }
                if (null == BeanHelper.getBean(fieldType)) { //如果bean中不存在就先set进bean去
                  BeanHelper.setBean(fieldType, fieldType.newInstance());  
                }
                field.set(BeanHelper.getBean(clazz), BeanHelper.getBean(fieldType));
              }else {
                //暂时不支持强制类型转换
              }
            }
            
          } catch (IllegalArgumentException e) {
            logger.error(e.toString());
          } catch (IllegalAccessException e) {
            logger.error(e.toString());
          } catch (InstantiationException e) {
            logger.error(e.toString());
          }
          
          
        }
        
      }
      
      
      
    }
    System.out.println("资源加载完成");
  }
  
}
